package com.example.rentsystem.servlet.api;

import com.example.rentsystem.entity.User;
import com.example.rentsystem.service.UserService;
import com.example.rentsystem.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Pattern;

@WebServlet("/modify-user-password")
public class ModifyUserPassServlet extends HttpServlet {

    UserService service;

    @Override
    public void init() throws ServletException {
        service = new UserServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("login-first", true);
            resp.sendRedirect("login");
            return;
        }
        String id = req.getParameter("id");
        if (id != null && !id.equals("")) {
            User u = service.getUserById(Integer.parseInt(id));
            String pass = req.getParameter("password");
            String repass = req.getParameter("repassword");
            if (!(pass.length() >= 8 && pass.length() <= 18)) {
                session.setAttribute("password-short", true);
                resp.sendRedirect("personal-info?id=" + user.getId());
                return;
            }
            if (!(repass.length() >= 8 && repass.length() <= 18)) {
                session.setAttribute("repassword-short", true);
                resp.sendRedirect("personal-info?id=" + user.getId());
                return;
            }
            if (!pass.equals(repass)) {
                session.setAttribute("password-not-equal", true);
                resp.sendRedirect("personal-info?id=" + user.getId());
                return;
            }
            u.setPassword(pass);
            service.editUser(u);
        }
        resp.sendRedirect("personal-info?id=" + user.getId());
    }
}
